//
//  RelationConfirmationViewController.m
//  nonghubao
//
//  Created by Fenrir on 13-10-29.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "RelationConfirmationViewController.h"
#import "ASImageView.h"
#import "RTLabel.h"
#import <QuartzCore/QuartzCore.h>
#import "JSONRequest.h"
#import "JMFBase.h"
#import "CirclePickerViewController.h"

@interface RelationConfirmationViewController ()<JSONRequestDelegate, CirclePickerDelegate>

@end

@implementation RelationConfirmationViewController
@synthesize invitationId = _invitationId;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor]; //RGBCOLOR(248, 248, 248);
    self.title = _L(@"vc_title_105");
    
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    ASImageView* imageView = [[ASImageView alloc] initWithFrame:CGRectMake(20, 20, 25, 25)];
    imageView.tag = 100;
    imageView.image = [UIImage imageNamed:@"dynamic_btn_001"];
    [self.view addSubview:imageView];
    
    RTLabel *infoLabel = [[RTLabel alloc] initWithFrame:CGRectMake(X_AND_WIDTH(imageView.frame)+10.0f, 17, 200.0f, 35.0f)];
    [self.view addSubview:infoLabel];
    infoLabel.lineSpacing = 5.0f;
    infoLabel.tag = 101;
    infoLabel.font = _SYS_FONT_002;
    
    //仿聊天泡泡背景
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(15.0f, Y_AND_HEIGHT(infoLabel.frame)+5.0f, 290.0f, 90.0f)];
    bgView.layer.masksToBounds = YES;
    bgView.layer.cornerRadius = 5.0f;
    bgView.layer.borderWidth = 1.0f;
    bgView.layer.borderColor = RGBCOLOR(200, 200, 200).CGColor;
    [self.view addSubview:bgView];
    
    //箭头
    UIImageView *arrowView = [[UIImageView alloc] initWithImage:LOADIMAGE(@"com_icon_012@2x", @"png")];
    arrowView.frame = CGRectMake(25.0f, Y_AND_HEIGHT(imageView.frame)+4.0f, 13.0f, 9.5f);
    [self.view addSubview:arrowView];
    
    UITextView *wordsTextView = [[UITextView alloc] initWithFrame:CGRectMake(20.0f, Y_AND_HEIGHT(infoLabel.frame)+10.0f, 280.0f, 80.0f)];
    wordsTextView.tag = 102;
    wordsTextView.editable = NO;
    wordsTextView.text = @"(无)";
    wordsTextView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:wordsTextView];
    
    //多功能按钮，“同意”邀请以及表示某一邀请信息的状态都要用到此按钮
    UIButton *defaultButton = [[UIButton alloc] initWithFrame:CGRectMake(10.0f, Y_AND_HEIGHT(bgView.frame)+10.0f, 300.0f, 46.0f)];
    defaultButton.tag = 103;
    [defaultButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:defaultButton];
    
    //忽略按钮
    UIButton *neglectButton = [[UIButton alloc] initWithFrame:CGRectMake(10.0f, Y_AND_HEIGHT(defaultButton.frame)+10.0f, 300.0f, 46.0f)];
    neglectButton.tag = 104;
    neglectButton.hidden = YES;
    [neglectButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [neglectButton setBackgroundImage:LOADIMAGE(@"com_btn_007_n@2x", @"png") forState:UIControlStateNormal];
    [neglectButton setTitle:_L(@"btn_title_08") forState:UIControlStateNormal];
    [self.view addSubview:neglectButton];
    
    //拒绝按钮
    UIButton *rejectButton = [[UIButton alloc] initWithFrame:CGRectMake(10.0f, Y_AND_HEIGHT(neglectButton.frame)+10.0f, 300.0f, 46.0f)];
    rejectButton.tag = 105;
    rejectButton.hidden = YES;
    [rejectButton setBackgroundImage:LOADIMAGE(@"com_btn_028_n@2x", @"png") forState:UIControlStateNormal];
    [rejectButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [rejectButton setTitle:_L(@"btn_title_09") forState:UIControlStateNormal];
    [self.view addSubview:rejectButton];
    
    [self invitationInfoRequest];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 事件

- (void)backButtonEvent
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)buttonEvent:(id)sender
{
    UIButton *clickedButton = (UIButton *)sender;
    
    //同意按钮就跳转到选择圈子页面
    if (clickedButton.tag == 103) {
        
        CirclePickerViewController* circlePickerVC = [[CirclePickerViewController alloc] initWithStyle:UITableViewStyleGrouped];
        
        circlePickerVC.delegate = self;
        
        UINavigationController* circleNavigationController = [[UINavigationController alloc] initWithRootViewController:circlePickerVC];
        
        [Helper navigationControllerCommonStyle:circleNavigationController];
        
        [self.navigationController presentModalViewController:circleNavigationController animated:true];
    
        return;
    }
    
    //忽略邀请和拒绝邀请操作
    NSString *url;

    if (clickedButton.tag == 104) {
        url = _JSON_URL_CIRCLE_FRIEND_INVITE_INGORE;
    }
    else if (clickedButton.tag == 105) {
        url = _JSON_URL_CIRCLE_FRIEND_INVITE_REFUSE;
    }
    else {
        
    }
    
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:url];
    request.delegate = self;
    request.hudOn = YES;
    request.hudTitle = _L(@"title_loading_01");
    [request setValue:@(_invitationId) forParameter:@"inviteId"];
    [request setSuccessSelector:@selector(inviteRequestDidFinished:)];
    [request asynchronous];
}

#pragma mark - 私有方法

//请求制定id的邀请信息
- (void)invitationInfoRequest
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_FRIEND_INVITE_INFO];
    request.delegate = self;
    request.hudOn = YES;
    request.hudTitle = _L(@"title_loading_01");
    [request setValue:@(_invitationId) forParameter:@"inviteId"];
    [request asynchronous];
}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        //邀请人的基本信息，头像、姓名和邀请验证信息
        [(ASImageView *)[self.view viewWithTag:100] setImageURL:[NSURL URLWithString:[jmf.data objectForKey:@"previewAvatar"]] andSourceImageURL:nil forStyle:PictureStyleCircleMemberAvart];
        [((RTLabel *)[self.view viewWithTag:101]) setText:[NSString stringWithFormat:@"%@<br><font color=gray>请求添加我为好友</font>", [jmf.data objectForKey:@"realName"]]];
        
        if ([[jmf.data objectForKey:@"description"] length] > 0) {
            
            [((UITextView *)[self.view viewWithTag:102]) setText:[jmf.data objectForKey:@"description"]];
        }
        else {
            [((UITextView *)[self.view viewWithTag:102]) setText:@"(无)"];
        }
        
        NSInteger status = [[jmf.data objectForKey:@"status"] integerValue];
        
        //0,未处理，1：同意 2：忽略，3：拒绝，4：删除
        if (status == 0) {
            [((UIButton *)[self.view viewWithTag:103]) setTitle:_L(@"btn_title_07") forState:UIControlStateNormal]; //同意
            [((UIButton *)[self.view viewWithTag:103]) setBackgroundImage:LOADIMAGE(@"com_btn_006_n@2x", @"png") forState:UIControlStateNormal];
            
            [self.view viewWithTag:104].hidden = NO;
            [self.view viewWithTag:105].hidden = NO;
        }
        
        else if (status == 1) {
            [((UIButton *)[self.view viewWithTag:103]) setTitle:_L(@"btn_title_10") forState:UIControlStateNormal]; //已同意
            [((UIButton *)[self.view viewWithTag:103]) setTitleColor:RGBCOLOR(150, 150, 150) forState:UIControlStateNormal];
            [((UIButton *)[self.view viewWithTag:103]) setBackgroundImage:LOADIMAGE(@"com_btn_037_n@2x", @"png") forState:UIControlStateNormal];
            ((UIButton *)[self.view viewWithTag:103]).enabled = NO;
        }
        
        else if (status == 2) {
            
            [((UIButton *)[self.view viewWithTag:103]) setTitle:_L(@"btn_title_11") forState:UIControlStateNormal]; //已忽略
            [((UIButton *)[self.view viewWithTag:103]) setTitleColor:RGBCOLOR(150, 150, 150) forState:UIControlStateNormal];
            [((UIButton *)[self.view viewWithTag:103]) setBackgroundImage:LOADIMAGE(@"com_btn_037_n@2x", @"png") forState:UIControlStateNormal];
            ((UIButton *)[self.view viewWithTag:103]).enabled = NO;
        }
        else if (status == 3) {
            
            [((UIButton *)[self.view viewWithTag:103]) setTitle:_L(@"btn_title_12") forState:UIControlStateNormal]; //已拒绝
            [((UIButton *)[self.view viewWithTag:103]) setTitleColor:RGBCOLOR(150, 150, 150) forState:UIControlStateNormal];
            [((UIButton *)[self.view viewWithTag:103]) setBackgroundImage:LOADIMAGE(@"com_btn_037_n@2x", @"png") forState:UIControlStateNormal];
            ((UIButton *)[self.view viewWithTag:103]).enabled = NO;
        }
        else {
            
        }
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

- (void)inviteRequestDidFinished:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:@"" andMessage:_L(@"title_networkunavailabe")];
}

#pragma mark - CirclePickerViewController Delegate

- (void)circlesPicked:(NSArray *)circles
{
    NSString *circleIds = @"";
    if (circles && circles.count != 0) {
        //将多个圈子ID用逗号隔开
        
        for (int i = 0; i < circles.count; i++) {
            
            //如果是最后一个则不添加“，”
            if (i == circles.count - 1) {
                circleIds = [circleIds stringByAppendingFormat:@"%@", [[circles objectAtIndex:i] objectForKey:@"id"]];
            }else{
                circleIds = [circleIds stringByAppendingFormat:@"%@,", [[circles objectAtIndex:i] objectForKey:@"id"]];
            }
        }
    }
    
    // 接收用户修改后或未修改的圈子
    // 如果最初的圈子数组为空，那么直接请求，如果不为空，那么判断内容是否一样，不一样则删除以前的再请求添加，
    // 一样则不管
    //circles为用户已选择的圈子数组，_cicleDataSource为服务器所返回的圈子数组，用户更新后_cicleDataSource也要跟着更新；
    
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_FRIEND_INVITE_CONSENT];
    
    [request setValue:circleIds forParameter:@"circleIds"];
    [request setValue:@(_invitationId) forParameter:@"inviteId"];
    NSDictionary* responseData = [request synchronous];
    
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:responseData];
    if (jmf.status != JMStatusSucceed) {
        [Helper easyShowJMFStatus:jmf];
        [self.navigationController popViewControllerAnimated:YES];
    }
}
@end
